package com.itlaobing.binary;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

@WebServlet("/myself/multipart")
@MultipartConfig(location = "D:/upload")
public class MyselfMultipartUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        throw new IllegalStateException("不支持 GET 方式");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        response.setHeader("content-type","text/html ; charset=UTF-8");

        PrintWriter out = response.getWriter();

        Collection<Part> parts = request.getParts();

        if (parts != null){
            for (Part part: parts) {
                String filename = part.getSubmittedFileName();

                //文件名不为 空 不为 空串
                if (filename!=null && filename.length() >0){
                    //文件内容保存在约定位置
                    part.write(filename);
                }

            }
            out.println("<div style='text-align:center ;'>");
            out.println("文件【 "  +"】上传成功");
            out.println("</div>");
            return;
        }
        out.println("<h3 align='center'> 上传失败</h3>");
    }
}
